package cn.tedu.sp11.filter;

import cn.tedu.sp01.util.JsonResult;
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;



@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        String serviceId = (String)requestContext.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request=requestContext.getRequest();
        String token=request.getParameter("token");
        if (StringUtils.isBlank(token)){
            requestContext.setSendZuulResponse(false);
            String json = JsonResult.err().code(JsonResult.NOT_LOGIN)
                    .msg("未登录")
//                    .msg("not login in")
                    .toString();
            requestContext.setResponseStatusCode(JsonResult.NOT_LOGIN);
            requestContext.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            requestContext.setResponseBody(json);
        }
        return null;

    }
}
